//import crypto from 'crypto'
import md5 from 'js-md5'
import website from '@/config/website'
import console from '@/util/console'

function formatNumber (n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function getYear (date) {
  const year = date.getFullYear()
  return year+'';
}

export function formatTimeYYMMDDhhmm (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  const minsecond = date.getMilliseconds()

  const t1 = [year, month, day].map(formatNumber).join('-')
  const t2 = [hour, minute].map(formatNumber).join(':')

  return `${t1} ${t2}`
}
export function formatTime (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  const minsecond = date.getMilliseconds()

  const t1 = [year, month, day].map(formatNumber).join('-')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}.${minsecond}`
}
export function formatTimes (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  const t1 = [year, month, day].map(formatNumber).join('-')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}
export function formatDate (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const t1 = [year, month, day].map(formatNumber).join('-')
  return `${t1} `
}

export function formatDateToYyyyMmDd (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const t1 = [year, month, day].map(formatNumber).join('')
  return `${t1}`
}

export function encodeMd5 (str) {
  let appid = website.clientSecret
  var encodeMd5Str = md5(str + appid) // password 加密完的密码
  return encodeMd5Str
}

export function transDate (date) {
  date = date.replace(/-/g, '/');
  var today = new Date()
  var todayEnd = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' 23:59:59'
  var tt = new Date(date)
  var days = parseInt((new Date(todayEnd).getTime() - tt.getTime()) / 86400000)
  var mouth = tt.getMonth() + 1
  var day = tt.getDate()  < 10 ? '0' + tt.getDate() : tt.getDate()
  var time = tt.getHours() < 10 ? '0' + tt.getHours() : tt.getHours()
  var min = tt.getMinutes() < 10 ? '0' + tt.getMinutes() : tt.getMinutes()
  var result
  if (days < 3) {
    if (days === 0) {
      result = '今天 ' + time + ':' + min
    } else if (days === 1) {
      result = '昨天 ' + time + ':' + min
    } else if (days === 2) {
      result = '前天 ' + time + ':' + min
    }
  } else {
    result = (mouth < 10 ? '0' + mouth : mouth) + '-' + day + ' ' + time + ':' + min
  }
  //console.log(' =result = ' + result)
  return result
}

// 实现日期格式的转化
export function formatDateToSpecificDate (date) {
  if (date) {
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    m = m < 10 ? ('0' + m) : m
    var d = date.getDate()
    d = d < 10 ? ('0' + d) : d
    return y + '年' + m + '月' + d + '日'
  } else {
    return date
  }
}
// 实现日期格式的转化为  1990.01.01
export function formatDateToSpotDate (date) {
  if (date) {
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    m = m < 10 ? ('0' + m) : m
    var d = date.getDate()
    d = d < 10 ? ('0' + d) : d
    return y + '/' + m + '/' + d
  } else {
    return date
  }
}

// 实现字符串时间格式转换为日期格式
export function stringToDate (dateStr, separator) {
  if (separator === null || separator === undefined) {
    separator = '-'
  }
  if (dateStr === null || dateStr === undefined) {
    return dateStr
  }

  var dateArr = dateStr.split(separator)
  var year = parseInt(dateArr[0])
  var month
  // 处理月份为04这样的情况
  if (dateArr[1].indexOf('0') == 0) {
    month = parseInt(dateArr[1].substring(1))
  } else {
    month = parseInt(dateArr[1])
  }
  var day = parseInt(dateArr[2])
  var date = new Date(year, month - 1, day)
  return date
}

/**
 * 计算两个时间段内的天数，包含周末
 * 
 * @param sDay(string) 开始时间
 * @param eDay(string) 结束时间
 * @returns
 */
export function countDays(sDay, eDay) {
  // eslint-disable-next-line no-redeclare
  var sDay = new Date(Date.parse(sDay.replace(/-/g, '/').substring(0, 10)));
  // eslint-disable-next-line no-redeclare
  var eDay = new Date(Date.parse(eDay.replace(/-/g, '/').substring(0, 10)));
  // 相差天数
  var diffDay = (eDay - sDay) / (1000 * 60 * 60 * 24) + 1;
  return diffDay;
}
/**
 * 计算两个时间段内的天数，不包含周末
 * @param {*} first 
 * @param {*} last 
 * @returns 
 */
export function getWorkday(first, last) {
  //console.log('first',first,end);
  //计算工作日方法：遍历这两个日期区间的每一个日期，获取他的getDay()
  //分别获取first和last的毫秒数(时间戳)
  first = new Date(first).getTime();
  last = new Date(last).getTime();

  var count = 0;
  for (var i = first; i <= last; i += 24 * 3600 * 1000) {
    var d = new Date(i);
    if (d.getDay() >= 1 && d.getDay() <= 5) {
      count++;
    }
  }
  return count;
}
/* 固定电话 */
export function validateTelephone (str) {
  const reg = /^((\d{3,4})|\d{3,4}-|\s)?\d{7,14}$/
  return reg.test(str)
}

/* 手机号码 */
export function validatePhoneNumber (str) {
  const reg = /^1[3456789]\d{9}$/
  return reg.test(str)
}

/* 手机号码和固定电话 */
export function validatePhTelNumber (str) {
  const reg = /^(((\d{3,4})|\d{3,4}-|\s)?\d{7,14})|([1][3,4,5,6,7,8,9][0-9]{9})$/
  return reg.test(str)
}

/* 电子邮箱 */
export function validateEmail (str) {
  const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
  return reg.test(str)
}

/* 邮编 */
export function validateZipCode (str) {
  const reg = /7[0-9]{5}$/
  return reg.test(str)
}

/* 身份证 */
export function validateIDCard (str) {
  const reg = /(\d{15}$)|(^\d{18}$)|(\d{17}(\d|X|x)$)/
  return reg.test(str)
}

/* 银行卡号 15位或者16位或者19位 */
export function validateBank (str) {
  const reg = /^([1-9]{1})(\d{14}|\d{18}|\d{15})$/
  return reg.test(str)
}
export function getBytesLength (str) {
  // 在GBK编码里，除了ASCII字符，其它都占两个字符宽
  // eslint-disable-next-line no-control-regex
  return str.replace(/[^\x00-\xff]/g, 'xx').length
}
// 生成序列随即数
export function getgenUnivalNo() {
  var now = new Date();
  var year = now.getFullYear(); //得到年份
  var month = now.getMonth() + 1;//得到月份
  var date = now.getDate();//得到日期
  var hour = now.getHours();//得到小时
  var minu = now.getMinutes();//得到分钟
  var sec = now.getSeconds();//得到秒
  var MS = now.getMilliseconds();//获取毫秒

  if (month < 10) month = '0' + month;
  if (date < 10) date = '0' + date;
  if (hour < 10) hour = '0' + hour;
  if (minu < 10) minu = '0' + minu;
  if (sec < 10) sec = '0' + sec;
  if (MS>= 10 &&MS < 100)
  {
    MS = '0' + MS;
  }
  else if(MS < 10)
  {
    MS = '00' + MS;
  }
  var univalNo = year+''+month+''+date+''+hour+''+minu+''+sec+''+MS+''+Math.floor(Math.random()*10)+''+Math.floor(Math.random()*10)+''+Math.floor(Math.random()*10);
  return univalNo;
}
//获取URL参数
export function UrlSearch(){
  let name,value,str=location.href,num=str.indexOf('?'); //取得整个地址栏
  let jsonObj = {};
  str=str.substr(num+1); //取得所有参数 stringvar.substr(start [, length ]
  let arr=str.split('&'); //各个参数放到数组里
  for(let i=0;i < arr.length;i++){
    num=arr[i].indexOf('=');
    if(num>0){
      name=arr[i].substring(0,num);
      value=arr[i].substr(num+1);
      jsonObj[name]=value;
    }
  }
  return jsonObj;
}
// 下划线转换驼峰
export function toHump(name) {
  return name.replace(/\_(\w)/g, function(all, letter){
    return letter.toUpperCase();
  });
}
// 驼峰转换下划线
export function toLine(name) {
  return name.replace(/([A-Z])/g,'_$1').toLowerCase();
}

export default {
  getYear,
  encodeMd5,
  formatNumber,
  formatTime,
  formatDate,
  transDate,
  formatTimes,
  formatTimeYYMMDDhhmm,
  stringToDate,
  formatDateToSpecificDate,
  validatePhoneNumber,
  validateEmail,
  getBytesLength,
  formatDateToSpotDate,
  formatDateToYyyyMmDd,
  getgenUnivalNo,
  countDays,
  getWorkday,
  UrlSearch,
  toHump,
  toLine,
}
